package com.jd.basic.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jd.basic.config.BussinessException;
import com.jd.basic.domain.Wxuser;
import com.jd.basic.dto.BinderDto;
import com.jd.basic.dto.LoginDto;
import com.jd.basic.dto.WeChatDto;
import com.jd.basic.eum.UserRegisterConstant;
import com.jd.basic.eum.WechatCons;
import com.jd.basic.jwt.JwtUtils;
import com.jd.basic.jwt.RsaUtils;
import com.jd.basic.jwt.UserInfo;
import com.jd.basic.mapper.LoginMapper;
import com.jd.basic.mapper.WxuserMapper;
import com.jd.basic.service.LoginService;
import com.jd.basic.util.AjaxResult;
import com.jd.basic.util.BusinessException;
import com.jd.basic.util.HttpUtil;
import com.jd.basic.util.MD5Utils;
import com.jd.org.domain.Employee;
import com.jd.org.domain.Shop;
import com.jd.org.mapper.EmployeeMapper;
import com.jd.org.mapper.ShopMapper;
import com.jd.sys.domain.Menu;
import com.jd.sys.mapper.MenuMapper;
import com.jd.sys.mapper.PermissionMapper;
import com.jd.user.domain.Logininfo;
import com.jd.user.domain.User;
import com.jd.user.mapper.LogininfoMapper;
import com.jd.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.print.attribute.standard.PrinterURI;
import javax.validation.constraints.NotBlank;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    LoginMapper loginMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Value("${jwt.pri}")
    private String jwtPri;
    /**
     * 微信扫码登陆接口
     *
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechat(WeChatDto dto) {
        System.err.println("微信Dto" + dto);
        // 1.参数校验
        // 2.请求微信的第二个接口 获取token和openiD
        String url = String.format(WechatCons.SECOND, WechatCons.APPID, WechatCons.SECRET, dto.getCode());
        String jsonStr = HttpUtil.httpGet(url);// 是个json字符串
        // 最好做个判断
        if (StringUtils.isBlank(jsonStr)) {
            throw new BusinessException("网络不通！");
        }
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        log.info("获取到的token和openid"+jsonStr);
        // 从里面取值 是get
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        // 再次判断
        if (StringUtils.isBlank(accessToken) || StringUtils.isBlank(openid)) {
            throw new BusinessException("网络不通！");
        }
        log.info("微信的openid+++++++++++++++++++++++++"+openid);
        // 3.根据openId 查询wxuser表 是否有数据
        Wxuser wxuser = wxuserMapper.findByOpenid(openid);
        if (null != wxuser) {
            // 根据WXuser里面的userId 寻找 logininfo数据
            Logininfo logininfo = logininfoMapper.findByUserId(wxuser.getUserId());
            // 有 则返回登陆成功 getMap
            Map<String, Object> map = this.getMap(logininfo);
            return AjaxResult.me().success(map);
        }
        // 没有 则返回resultObj = nobinder
        StringBuffer sbr = new StringBuffer()
                .append("?accessToken=")
                .append(accessToken)
                .append("&openId=").append(openid);
        // 我们现在返回的是 success:false  msg:nobinder  resultObj:"?accessToken=xxxx&openId=yyy"
        return AjaxResult.me().fail("nobinder").setResultObj(sbr);
    }

    // 绑定
    @Override
    public AjaxResult binder(BinderDto dto) {
        // 1.参数校验
        // 判断手机号验证码是否正确
        String phoneCode = (String) redisTemplate.opsForValue().get(String.format(UserRegisterConstant.BINDER_CODE_KEY, dto.getPhone()));
        if (StringUtils.isBlank(phoneCode) || !dto.getPhoneCode().equals(phoneCode)) {
            throw new BusinessException("验证码错误！");
        }
        // 2.根据token和openId调用第三个接口
        String url = String.format(WechatCons.THIRD, dto.getToken(), dto.getOpenId());
        String jsonStr = HttpUtil.httpGet(url);
        if (StringUtils.isBlank(jsonStr)) {
            throw new BusinessException("微信叒炸了！");
        }
        // jsonObject 会将json字符串直接转成对象 前提：字段要一样
        Wxuser wxuser = JSONObject.parseObject(jsonStr, Wxuser.class);
        // 最好再做个判断
        if (null == wxuser) {
            throw new BusinessException("微信叕炸了！");
        }
        // 根据手机号查询user里面是否有数据
        User user = userMapper.findByPhone(dto.getPhone());
        Logininfo logininfo = new Logininfo();
        if (null == user) {
            // 没有 添加三张表
            user = dto.getUser();
            // 0.1.添加logininfo
            BeanUtils.copyProperties(user, logininfo);
            logininfo.setDisable(true);
            logininfo.setType(1);

            logininfoMapper.add(logininfo);
            // 0.2.添加user
            user.setLogininfoId(logininfo.getId());
            System.err.println(user);
            userMapper.add(user);
        }else {
            logininfo =  logininfoMapper.findByUserId(user.getId());
        }
        System.err.println("头像" + wxuser.getHeadimgurl());
        logininfo.setHeadImg(wxuser.getHeadimgurl());
        // 0.3.添加wxuser
        // 有 直接绑定wxuser
        wxuser.setUserId(user.getId());
        // 添加wxuser数据
        wxuserMapper.add(wxuser);
        // 返回登陆成功
        Map<String, Object> map = this.getMap(logininfo);
        System.err.println("微信" +wxuser);
        System.err.println("用户" + user);
        System.err.println("返回结果map" + map);
        return AjaxResult.me().success(map);
    }

    @Override
    public AjaxResult login(LoginDto dto) {
        // 先判断账号是否存在
        Logininfo logininfo = loginMapper.findByName(dto.getUsername());
        if (null == logininfo){
            throw new BussinessException("账号不存在,请核对后输入");
        }
        // 然后判断密码是否匹配
        String passParam = dto.getPassword(); // 这个只是一个数字
        // 需要拼接上盐值
        String passMd5 = MD5Utils.encrypByMd5(logininfo.getSalt() + passParam);
        System.err.println("加密后的密码" + passMd5);
        // 数据库里加密过后的密码
        String passwordDb = logininfo.getPassword();
        System.err.println("数据库里的密码" + passwordDb);
        if (null == passMd5 || !passMd5.equals(passwordDb)){
            throw new BussinessException("密码错误,烂裤东");
        }
        System.err.println("用户信息Logininfo" + logininfo);

        // 返回给前端的数据
        Map<String, Object> map = getMap(logininfo);
        return AjaxResult.me().success(map);
    }



    // 返回给前端数据的方法
    public Map<String,Object> getMap(Logininfo logininfo) {
        // 定义用于返回给前端数据的map

        HashMap<String, Object> map = new HashMap<>();
        // 获取jwt的公钥
        PrivateKey privateKey = null;
        try {
            privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(jwtPri).getFile());
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用公钥生成token
        UserInfo userInfo = new UserInfo();
        userInfo.setLogininfo(logininfo);

        // 如果是后台登录才有 菜单按钮等权限 前台登录没有 做一次判断type
        if (0 == logininfo.getType()){

            List<Menu> menus = menuMapper.findByLogininfoId(logininfo.getId());
            System.err.println("菜单" + menus);
            userInfo.setMenus(menus);
            List<String> permissions = permissionMapper.findByLogininfoId(logininfo.getId());
            System.err.println("权限" + permissions);
            userInfo.setPermissions(permissions);
            map.put("menus",menus);
            map.put("permissions",permissions);
            // 根据logininfoid 去查询当前让你的店铺 首先你得是店铺的员工
            Employee emp = employeeMapper.findByLogininfoId(logininfo.getId());
            if (null != emp && null != emp.getShopId()){
                Shop shop =  shopMapper.findById(emp.getShopId());
                userInfo.setShop(shop);
            }
        }
        // 生成token
        String token = JwtUtils.generateTokenExpireInSeconds(userInfo, privateKey, 9999999);
        // 保护隐私 清楚账号和手机号数据
        logininfo.setPhone("*****");
        logininfo.setPassword("*****");
        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;
    }
}
